package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.message.ArticleForEsConstants;
import com.heima.common.constants.message.NewsAutoScanConstants;
import com.heima.common.constants.message.WmNewsMessageConstants;
import com.heima.common.constants.wemedia.WemediaConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.NewsAuthDto;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vo.WmNewsVo;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @作者 itcast
 * @创建日期 2021/4/15 9:19
 **/
@Service
@Slf4j
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;
    @Autowired
    WmMaterialMapper wmMaterialMapper;


    @Override
    public ResponseResult findAll(WmNewsPageReqDto wmNewsPageReqDto) {
        // 1. 校验参数
        wmNewsPageReqDto.checkParam();
        // 2. 封装查询条件
        LambdaQueryWrapper<WmNews> queryWrapper = Wrappers.<WmNews>lambdaQuery();
        //    状态查询条件
        if(wmNewsPageReqDto.getStatus() != null){
            queryWrapper.eq(WmNews::getStatus,wmNewsPageReqDto.getStatus());
        }
        //    关键字查询条件
        if(StringUtils.isNotBlank(wmNewsPageReqDto.getKeyword())){
            queryWrapper.like(WmNews::getTitle,wmNewsPageReqDto.getKeyword());
        }
        //    频道查询条件
        if(wmNewsPageReqDto.getChannelId() != null){
            queryWrapper.eq(WmNews::getChannelId,wmNewsPageReqDto.getChannelId());
        }
        //    发布时间区间查询条件
        if(wmNewsPageReqDto.getBeginPubDate() != null && wmNewsPageReqDto.getEndPubDate()!=null){
            // 用发布时间作为条件    在   beginPubDate   和   endPubDate 区间的条件
            queryWrapper.between(WmNews::getPublishTime,wmNewsPageReqDto.getBeginPubDate(),wmNewsPageReqDto.getEndPubDate());
        }
        //    根据当前登录用户ID 查询条件
        Integer userId = WmThreadLocalUtils.getUser().getId();
        queryWrapper.eq(WmNews::getUserId,userId);
        //    分页查询条件
        Page<WmNews> pageReq = new Page(wmNewsPageReqDto.getPage(), wmNewsPageReqDto.getSize());
        //    按照文章创建时间  降序排序
        queryWrapper.orderByDesc(WmNews::getCreatedTime);

        IPage<WmNews> pageResult = page(pageReq, queryWrapper);
        // 3. 返回结果   返回结果添加图片访问前缀
        PageResponseResult pageResponseResult = new PageResponseResult(wmNewsPageReqDto.getPage(), wmNewsPageReqDto.getSize(), (int) pageResult.getTotal());
//        List<WmNews> records = pageResult.getRecords();
//        for (WmNews record : records) {
//            String images = record.getImages(); // 取出封面图片
//            if(StringUtils.isNotBlank(images)){
//                // 得到图片路径数据流
//                String imgUrl = Arrays.stream(images.split(",")) // 准备好数据流
//                        .map((url) -> webSite + url)  // 中间操作  为每一个路径添加 访问前缀
//                        .collect(Collectors.joining(","));// 终止操作  收集结果，并将结果根据 ,号 拼接成一个字符串
//                record.setImages(imgUrl);
//            }
//        }
        pageResponseResult.setData(pageResult.getRecords());
        pageResponseResult.setHost(webSite);
        return pageResponseResult;
    }

    /**
     * 保存或修改 自媒体文章
     * @param wmNewsDto  文章数据
     * @param isSubmit  是否为提交 1 提交 0 草稿
     * @return
     */
    @Transactional
    @Override
    public ResponseResult submitNews(WmNewsDto wmNewsDto, Short isSubmit) {

        // 1. 检查参数 封装成一个wmNews对象
        if(StringUtils.isBlank(wmNewsDto.getContent())){
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID,"文章内容不能为空");
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if(user == null || user.getId() == null){
            throw new CustomException(AppHttpCodeEnum.NO_OPERATOR_AUTH,"登录之后才能发表文章");
        }
        WmNews wmNews = new WmNews();
        // 将入参的属性 拷贝到 wmNews中
        BeanUtils.copyProperties(wmNewsDto,wmNews);
        // 判断封面图片类型 是否为自动 如果自动 暂时设置为null
        if(wmNewsDto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)){
            wmNews.setType(null);
        }
        // 封面图片 入参为list<String>集合  转成 字符串  多个图片 ,号拼接
        List<String> images = wmNewsDto.getImages();
        if(images!=null && !images.isEmpty()){
            wmNews.setImages(
                    images.stream()  // 获取流
                            .map((url) -> url.replace(webSite, ""))  // 对流数据的中间操作
                            .collect(Collectors.joining(","))); // 终止操作
        }
        wmNews.setUserId(user.getId());
        // 2. 保存或修改wmNews
        saveOrUpdateWmNews(wmNews);
        if(isSubmit.equals(WemediaConstants.WM_NEWS_SUMMIT_STATUS)){
            //  抽取 文章内容中 所保存的 所有图片路径 ==>  imageList
            List<String> materialUrlList = parseContentImages(wmNewsDto.getContent());
            // 3. 判断是提交还是草稿  如果提交需要保存内容和素材的关联关系
            // xxxx.jpg    aaaa.jpg    bbbb.jpg     wmNewsId     type: 0
            if(materialUrlList!=null && !materialUrlList.isEmpty()){
                saveRelativeInfoForContent(materialUrlList,wmNews.getId(),WemediaConstants.WM_CONTENT_REFERENCE);
            }
            // 4. 判断是提交还是草稿  如果提交需要保存封面和素材的关联关系
            saveRelativeInfoForCover(materialUrlList,wmNews,wmNewsDto);
            Map map = new HashMap();
            map.put("wmNewsId",wmNews.getId());
            log.info("文章提交待审核成功,并发送kafka消息 ==> {}",wmNews.getId());
            kafkaTemplate.send(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_TOPIC, JSON.toJSONString(map));
        }
        return ResponseResult.okResult();
    }

    @Autowired
    KafkaTemplate<String,String> kafkaTemplate;

    @Override
    public ResponseResult findWmNewsById(Integer id) {
        // 1. 检查参数
        if(id == null){
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2. 根据id查询文章信息
        WmNews wmNews = getById(id);
        if(wmNews == null){
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        // 3. 返回结果  host==> 添加访问前缀路径
        ResponseResult responseResult = ResponseResult.okResult(wmNews);
        responseResult.setHost(webSite);
        return responseResult;
    }

    @Override
    public ResponseResult delNews(Integer id) {
        // 1. 检查参数 判断是否登录
        if(id == null){
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if(user == null){
            throw new CustomException(AppHttpCodeEnum.NO_OPERATOR_AUTH,"请登录之后在操作");
        }
        // 2. 根据id查询文章
        WmNews wmNews = getOne(Wrappers.<WmNews>lambdaQuery().eq(WmNews::getId, id).eq(WmNews::getUserId, user.getId()));
        if(wmNews == null){
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST,"未查询到相关文章信息");
        }
        // 3. 如果文章状态为9(发布) 并且 上架状态: 1(上架) 不可以删除
        if(wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())&&wmNews.getEnable() == 1){
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST,"当前文章已发布，请先下架后再删除");
        }
        // 4. 删除文章与素材的关联关系
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,id));
        // 5. 删除文章信息
        removeById(id);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        // 1. 检查参数  判断id不能为空   enable ( 0   1 )
        if(dto.getId() == null || dto.getEnable() == null){
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        if(!dto.getEnable().equals(WemediaConstants.WM_NEWS_DOWN)&&!dto.getEnable().equals(WemediaConstants.WM_NEWS_UP)){
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID,"文章上下架参数错误");
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if(user == null){
            throw new CustomException(AppHttpCodeEnum.NO_OPERATOR_AUTH,"请先登录");
        }
        // 2. 根据id查询出文章数据
        WmNews one = getOne(Wrappers.<WmNews>lambdaQuery().eq(WmNews::getId, dto.getId()).eq(WmNews::getUserId, user.getId()));
        if(one == null){
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST,"未查询到该文章");
        }
        // 3. 判断文章状态是否为9(发布)   发布状态的文章才可以上下架
        if(!one.getStatus().equals(WmNews.Status.PUBLISHED.getCode())){
            throw new CustomException(AppHttpCodeEnum.DATA_STATUS_ERROR,"只有发布状态的文章才可以上下架");
        }
        // 4. 根据 id 修改 文章的 enable字段
        update(Wrappers.<WmNews>lambdaUpdate().set(WmNews::getEnable,dto.getEnable()).eq(WmNews::getId,dto.getId()));
        // wmNews = articleId    enable: 上下架
        if(one.getArticleId()!=null){
            Map map = new HashMap();
            map.put("articleId",one.getArticleId());
            map.put("enable",dto.getEnable());
            log.info("文章上下架发送通知   主题: {} , 消息内容: {}",WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC,map);
            kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC,JSON.toJSONString(map));
            //是否上架  0 下架  1 上架
            // ==============新加代码==============================================
            if(dto.getEnable().intValue() == 0){
                kafkaTemplate.send(ArticleForEsConstants.ARTICLE_ELASTICSEARCH_DELETE,JSON.toJSONString(map));
            }else {
                kafkaTemplate.send(ArticleForEsConstants.ARTICLE_ELASTICSEARCH_ADD,JSON.toJSONString(map));
            }
            // ==============新加代码==============================================
        }
        return ResponseResult.okResult();
    }





    @Override
    public List<Integer> findRelease() {
        // 查询  状态为 4 或 8   发布时间 小于等于 当前时间  的 所有文章id集合
        List<WmNews> list = list(Wrappers.<WmNews>lambdaQuery().in(WmNews::getStatus, 4, 8).le(WmNews::getPublishTime, new Date()));
        if(list != null && !list.isEmpty()){
            return list.stream().map(WmNews::getId).collect(Collectors.toList());
        }
        return null;
    }

    @Autowired
    WmNewsMapper wmNewsMapper;



    @Override
    public ResponseResult findList(NewsAuthDto dto) {
        // 1. 校验参数
        dto.checkParam();
        // 2. 分页查询
        if(StringUtils.isNotBlank(dto.getTitle())){
            dto.setTitle("%"+dto.getTitle()+"%");
        }
        Integer currentPage = dto.getPage();
        dto.setPage((currentPage - 1)*dto.getSize());
        // 查询分页数据
        List<WmNewsVo> listAndPage = wmNewsMapper.findListAndPage(dto);
        // 查询满足条件的总记录数
        long listCount = wmNewsMapper.findListCount(dto);
        // 3. 封装返回结果
        PageResponseResult pageResponseResult = new PageResponseResult(currentPage,dto.getSize(),(int)listCount);
        pageResponseResult.setData(listAndPage);
//        pageResponseResult.setHost();
        return pageResponseResult;
    }

    @Autowired
    WmUserMapper wmUserMapper;

    @Override
    public ResponseResult findWmNewsVo(Integer id) {
        // 1. 检查参数
        if(id == null){
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2. 根据id查询wm_news
        WmNews wmNews = getById(id);
        if(wmNews == null){
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST,"文章数据不存在");
        }
        // 3. 查询WmUser
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        if(wmUser == null){
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST,"作者信息不存在");
        }
        WmNewsVo wmNewsVo = new WmNewsVo();
        BeanUtils.copyProperties(wmNews,wmNewsVo);
        wmNewsVo.setAuthorName(wmUser.getName());
        // 4. 返回给前端  ( webSite)
        ResponseResult responseResult = ResponseResult.okResult(wmNewsVo);
        responseResult.setHost(webSite);
        return responseResult;
    }
    // status : 2 未通过    4  通过
    @Override
    public ResponseResult updateStatus(Short status, NewsAuthDto dto) {
        // 校验参数  dto  id
        if(dto.getId() == null){
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 根据id查询文章
        WmNews wmNews = getById(dto.getId());
        if(wmNews == null){
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST,"文章数据不存在");
        }
        // 修改 文章 status字段
        wmNews.setStatus(status);
        if (StringUtils.isNotBlank(dto.getMsg())) {
            wmNews.setReason(dto.getMsg());
        }
        updateById(wmNews);
        return ResponseResult.okResult();
    }
    /**
     * 保存  封面 与  素材的关联关系
     * @param materialUrlList 图片url列表
     * @param wmNews
     * @param wmNewsDto
     */
    private void saveRelativeInfoForCover(List<String> materialUrlList, WmNews wmNews, WmNewsDto wmNewsDto) {
        // 1. 获取请求中的文章封面图片列表
        List<String> images = wmNewsDto.getImages();
        // 2. 判断当前封面图片类型是否是  自动生成
        if (wmNewsDto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            if(materialUrlList!=null && !materialUrlList.isEmpty()){
                // 内容图片列表不为空
                int imgNum = materialUrlList.size();
                if(imgNum <= 2){ // 单图
                    wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                    //  图1.jpg   图2.jpg
                    images = materialUrlList.stream().limit(1).collect(Collectors.toList());
                }else { // 多图
                    wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                    images = materialUrlList.stream().limit(3).collect(Collectors.toList());
                }
                // 图1.jpg   图2.jpg
                wmNews.setImages(images.stream()
                        .map(url -> url.replace(webSite,""))
                        .collect(Collectors.joining(",")));//
            }else {
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }
            // 因为 自动生成图片， 对wmNews对象类型 和 images封面图字段做了修改
            // 需要重新保存
            updateById(wmNews);
        }
        if(images !=null && !images.isEmpty()){
            images = images.stream() // 去除url 前缀
                    .map(url -> url.replace(webSite, ""))
                    .collect(Collectors.toList());
            // 保存封面图片  与  素材的关联关系
            saveRelativeInfo(images,wmNews.getId(),WemediaConstants.WM_IMAGE_REFERENCE);
        }
    }

    private void saveRelativeInfoForContent(List<String> materialUrlList, Integer newId, Short wmContentReference) {
        saveRelativeInfo(materialUrlList,newId,wmContentReference);
    }



    /**
     * 保存关联关系的方法
     * @param materialUrlList 素材图片路径
     * @param newId  文章ID
     * @param type 引用类型 0 内容引用     1 封面引用
     */
    private void saveRelativeInfo(List<String> materialUrlList, Integer newId, Short type) {
        // 1. 根据图片路径 及 登录用户  查询出 相关素材ID列表
        // select * from wm_material  where url in (路径1.jpg , 路径2.jpg, 路径3.jpg) and userId = ?
        List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(
                Wrappers.<WmMaterial>lambdaQuery()
                        .in(WmMaterial::getUrl, materialUrlList)
                        .eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser().getId())
        );
        if(wmMaterials == null || wmMaterials.size() == 0){
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST,"查询素材信息失败");
        }
        // 2. 检查所有素材是否全部存在   wmMaterials ==> 转为Map ==>   key: url     value: id
        List<Integer> materialIdList = new ArrayList<>();
        Map<String, Integer> urlAndIdMap = wmMaterials.stream()
                .collect(Collectors.toMap(WmMaterial::getUrl, WmMaterial::getId));
        for (String materialUrl : materialUrlList) {
            if(urlAndIdMap.get(materialUrl) == null){
                throw  new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST,"素材数据不存在");
            }
            materialIdList.add(urlAndIdMap.get(materialUrl));
        }
        // 3. 得到的素材ID  和  文章ID  及   引用类型  保存关联关系
        wmNewsMaterialMapper.saveRelations(materialIdList,newId,type);
    }

    /**
     * 抽取文章内容中 所包含的 所有素材路径
     * @param content
     * @return
     */
    private List<String> parseContentImages(String content) {
        // 将 json字符串转为 map集合
        List<Map> contentList = JSONArray.parseArray(content,Map.class);
        return contentList.stream()
                .filter(this::isImage)
                .map((map) -> (String) map.get("value"))
                .map(imageUrl -> imageUrl.replace(webSite, ""))
                .collect(Collectors.toList());
//        for (Map map : contentList) {
//            if(map.get("type").equals(WemediaConstants.WM_NEWS_TYPE_IMAGE)){
//                String imageUrl = (String)map.get("value");
//                imageUrl = imageUrl.replace(webSite,"");
//                materialUrlList.add(imageUrl);
//            }
//        }
//        return materialUrlList;
    }

    /**
     * 判断 是否为图片类型
     * @param map
     * @return
     */
    private boolean isImage(Map map){
        return map.get("type").equals(WemediaConstants.WM_NEWS_TYPE_IMAGE);
    }

    /**
     * 保存 或 修改文章的 方法
     * @param wmNews
     */
    private void saveOrUpdateWmNews(WmNews wmNews) {
        if(wmNews.getId() ==null){
            // 添加文章
            wmNews.setCreatedTime(new Date());
            wmNews.setEnable((short)1);
            wmNews.setSubmitedTime(new Date());
            save(wmNews); // 保存文章
        }else {
            // 删除素材 和 文章的关联关系
            wmNewsMaterialMapper.delete(
                    Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,wmNews.getId())
            );
            // 修改文章
            updateById(wmNews);
        }
    }

    @Value("${file.oss.web-site}")
    String webSite;

}
